<?php
/**
* @copyright	Copyright (C) 2005 - 2007 Open Source Matters. All rights reserved.
* @license		GNU/GPL, see LICENSE.php
* Joomla! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
* See COPYRIGHT.php for copyright notices and details.
**/

// no direct access
defined( '_JEXEC' ) or die( 'Restricted access' );

class TemplateAdminClass
{
	var $_db;

	var $_error;

	function TemplateAdminClass()
	{
		$this->_db = &JFactory::getDBO();
		$this->_error = false;
	}


	function loadBannerList()
	{
		$query = "SELECT b.id, b.title, b.file, b.menu_item, m.name,m.menutype, m.link, m.id AS mid FROM #__template_banner AS b"
		       . "\n INNER JOIN #__menu AS m ON m.id = b.menu_item"
		       . "\n ORDER BY b.id ASC";
		       $this->_db->setQuery($query);
		       $rows = $this->_db->loadObjectList();

		if(!is_array($rows)) { $rows = array(); }

		return $rows;
	}


	function loadBanner($id)
	{
        $query = "SELECT id, title, file, menu_item FROM #__template_banner WHERE id = '$id'";
               $this->_db->setQuery($query);
               $row = $this->_db->loadObject();

        return $row;
	}


	function loadMenuItems()
	{
		$query = "SELECT m.id, m.menutype, m.name, b.id AS occupied,b.title FROM #__menu AS m"
		       . "\n LEFT JOIN #__template_banner AS b ON b.menu_item = m.id"
		       . "\n WHERE m.published = '1'"
		       . "\n ORDER BY m.menutype, m.name ASC";
		       $this->_db->setQuery($query);
		       $rows = $this->_db->loadObjectList();

		if(!is_array($rows)) { $rows = array(); }

		return $rows;
	}


	function validate_addBanner($banner = '', $cids = array())
	{
        if(!$banner) {
        	$this->_error = JTEXT::_("Please select a banner");
        }

        if(!getimagesize($banner)) {
        	$this->_error = JTEXT::_("The file you are trying to upload is not a valid image");
        }

        if(!count($cids)) {
        	$this->_error = JTEXT::_("Please select a menu item");
        }
	}


	function validate_updateBanner($banner = '', $cids = array())
	{
        if($banner && !getimagesize($banner)) {
        	$this->_error = JTEXT::_("The file you are trying to upload is not a valid image");
        }

        if(!count($cids)) {
        	$this->_error = JTEXT::_("Please select a menu item");
        }
	}


	function saveBanner($tmp_file, $filename, $cids)
	{
		jimport('joomla.client.helper');
		jimport('joomla.filesystem.file');

		$ftp = JClientHelper::getCredentials('ftp');

        // try to make the banner directory writeable
        if (!$ftp['enabled'] && JPath::isOwner(JPATH_TMPL_BANNER) && !JPath::setPermissions(JPATH_TMPL_BANNER, '0777')) {
            $this->_error = JText::_('Banner directory is unwriteable');
            return false;
        }

        $destination = JPATH_TMPL_BANNER.DS.$filename;

        if(!JFile::upload($tmp_file, $destination)) {
        	$this->_error = JText::_('Could not upload file');
            return false;
        }

        // make banner directory back unwriteable
        JPath::setPermissions(JPATH_TMPL_BANNER, '0755');

		foreach ($cids AS $cid)
		{
			if(!JFile::copy($destination,  JPATH_TMPL_BANNER.DS.$cid.$filename)) {
				$this->_error = JText::_('Could not copy file');
			}

			$query = "INSERT INTO #__template_banner VALUES(NULL, '$filename', '".$cid.$filename."', '$cid')";
			       $this->_db->setQuery($query);
			       $this->_db->query();
		}

		JFile::delete($destination);

		return JText::_("Your banner has been created");
	}


	function updateBanner($tmp_file, $filename, $cids, $id)
	{
		jimport('joomla.client.helper');
		jimport('joomla.filesystem.file');

		$ftp = JClientHelper::getCredentials('ftp');

		// try to make the banner directory writeable
        if (!$ftp['enabled'] && JPath::isOwner(JPATH_TMPL_BANNER) && !JPath::setPermissions(JPATH_TMPL_BANNER, '0777')) {
            $this->_error = JText::_('Banner directory is unwriteable');
            return false;
        }

        $destination = JPATH_TMPL_BANNER.DS.$filename;

        if($tmp_file) {
        	if(!JFile::upload($tmp_file, $destination)) {
        	   $this->_error = JText::_('Could not upload file');
               return false;
            }

            // make banner directory back unwriteable
            JPath::setPermissions(JPATH_TMPL_BANNER, '0755');

            $row = new stdClass();
        	$row->title = $filename;
        	$row->file  = $filename;

        	$query = "SELECT file FROM #__template_banner WHERE id = '$id'";
                   $this->_db->setQuery($query);
                   $old_banner = $this->_db->loadResult();

            if($old_banner) {
            	if(!JFile::delete(JPATH_TMPL_BANNER.DS.$old_banner)) {
                    $this->_error = JText::_('Could not delete old file');
            	}
            }
        }
        else {
        	$query = "SELECT title, file FROM #__template_banner WHERE id = '$id'";
                   $this->_db->setQuery($query);
                   $row = $this->_db->loadObject();
        }

        $query = "DELETE FROM #__template_banner WHERE id = '$id'";
               $this->_db->setQuery($query);
               $this->_db->query();

		foreach ($cids AS $cid)
		{
			if($tmp_file) {
				if(!JFile::copy($destination,  JPATH_TMPL_BANNER.DS.$cid.$filename)) {
				   $this->_error = JText::_('Could not copy file');
			    }
			    $new_name = $cid.$filename;
			}
			else {
               if(!JFile::copy(JPATH_TMPL_BANNER.DS.$row->file,  JPATH_TMPL_BANNER.DS.$cid.$row->file)) {
				   $this->_error = JText::_('Could not copy file');
			    }
			    $new_name = $cid.$row->file;
			}

			$query = "INSERT INTO #__template_banner VALUES(NULL, '$row->title', '".$new_name."', '$cid')";
			       $this->_db->setQuery($query);
			       $this->_db->query();
		}

		if($tmp_file) {
			JFile::delete($destination);
		}
		else {
			JFile::delete(JPATH_TMPL_BANNER.DS.$row->file);
		}

		return JText::_('Your banner has been updated');
	}


	function deleteBanners($cids)
	{
        $cids = implode(',', $cids);

        jimport('joomla.filesystem.file');

        $query = "SELECT file FROM #__template_banner WHERE id IN($cids)";
               $this->_db->setQuery($query);
               $images = $this->_db->loadResultArray();

        if(!is_array($images)) { $images = array(); }

        foreach ($images AS $image)
        {
        	if(!JFile::delete(JPATH_TMPL_BANNER.DS.$image)) {
                $this->_error = JText::_('Could not delete old file');
        	}
        }

        $query = "DELETE FROM #__template_banner WHERE id IN($cids)";
               $this->_db->setQuery($query);
               $this->_db->query();

        return JText::_("The selected banners have been deleted");
	}


	function loadImageDir()
	{
        $images = array();

        if ($handle = opendir(JPATH_TMPL_IMAGES)) {

           while (false !== ($file = readdir($handle)))
           {
               if(@getimagesize(JPATH_TMPL_IMAGES.DS.$file)) {
           	       array_push($images,$file);
               }
           }

           closedir($handle);
        }

        return $images;
	}


	function updateImage($tmp, $replace)
	{
       if(!file_exists(JPATH_TMPL_IMAGES.DS.$replace)) {
       	  $this->_error = JText::_("The file you want to replace does not exist");
       	  return false;
       }

       jimport('joomla.client.helper');
	   jimport('joomla.filesystem.file');

	   $ftp = JClientHelper::getCredentials('ftp');

	   // try to make the banner directory writeable
        if (!$ftp['enabled'] && JPath::isOwner(JPATH_TMPL_BANNER) && !JPath::setPermissions(JPATH_TMPL_IMAGES, '0777')) {
            $this->_error = JText::_('Banner directory is unwriteable');
            return false;
        }

       if(JFile::delete(JPATH_TMPL_IMAGES.DS.$replace)) {
       	  if(!JFile::upload($tmp, JPATH_TMPL_IMAGES.DS.$replace)) {
       	  	 $this->_error = JText::_('Could not upload file');
             return false;
       	  }
       }
       else {
       	  $this->_error = JText::_('Could not delete old file');
          return false;
       }

       JPath::setPermissions(JPATH_TMPL_IMAGES, '0755');

       return JText::_("The selected images have been replaced");
	}


	function showMessage( $message = '', $exit = true)
	{
		global $mainframe;

        if($this->_error) {
           echo "<script type='text/javascript'>
                 window.parent.document.getElementById('templateAdmin_debug').innerHTML = '<span class=\'alert\'>$this->_error</span>';
                 window.parent.document.getElementById('sbox-window').close();
                 </script>";
        }
        else {
        	echo "<script type='text/javascript'>
                  window.parent.document.getElementById('templateAdmin_debug').innerHTML = '<span class=\'info\'>$message</span>';
                  window.parent.document.getElementById('sbox-window').close();
                  </script>";
        }

        if($exit) {
        	$mainframe->close();
        }

	}
}
?>